package com.macro.mall.controller;

import com.macro.mall.common.api.CommonResult;
import com.macro.mall.dto.ImgUploadRes;
import com.macro.mall.service.OssFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 */
@Api(tags = "FileController", description = "文件上传下载管理")
@Controller
@RequestMapping("/file")
public class FileController {

  private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);

  @Autowired
  private OssFileService ossFileService;

  @ApiOperation("文件上传")
  @RequestMapping(value = "/image/upload", method = RequestMethod.POST)
  @ResponseBody
  public CommonResult<?> upload(@RequestParam("file") MultipartFile file) {
    try {
      String filename = file.getOriginalFilename();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
      // 设置存储对象名称
      String objectName = sdf.format(new Date()) + "/" + filename;
      String url = ossFileService.save(objectName, file.getInputStream(), file.getContentType());
      ImgUploadRes imgUploadRes = new ImgUploadRes();
      imgUploadRes.setName(filename);
      imgUploadRes.setUrl(url);
      return CommonResult.success(imgUploadRes);
    } catch (Exception e) {
      LOGGER.info("上传发生错误: {}！", e.getMessage());
    }
    return CommonResult.failed();
  }

  @ApiOperation("文件删除")
  @RequestMapping(value = "/image/delete", method = RequestMethod.POST)
  @ResponseBody
  public CommonResult<?> delete(@RequestParam("objectName") String objectName) {
    try {
      ossFileService.delete(objectName);
      return CommonResult.success();
    } catch (Exception e) {
      LOGGER.error("删除失败", e);
    }
    return CommonResult.failed();
  }
}
